package com.zmn.plat.business.impl.servcategory;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.business.interfaces.servcategory.CategoryFaultImageBService;
import com.zmn.plat.common.constant.BaseCodeMapConsts;
import com.zmn.plat.common.dictionary.PlatErrorCodeDict;
import com.zmn.plat.common.dto.base.FaultImageDRO;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.common.util.StringToArrayUtil;
import com.zmn.plat.model.entity.base.fault.Fault;
import com.zmn.plat.model.entity.base.fault.FaultQuery;
import com.zmn.plat.model.entity.product.BaseCodeMap;
import com.zmn.plat.model.entity.product.BaseCodeMapQuery;
import com.zmn.plat.model.entity.servcategory.CategoryFaultImage;
import com.zmn.plat.model.entity.servcategory.CategoryFaultImageQuery;
import com.zmn.plat.model.entity.servcategory.ServAssCategoryQuery;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;
import com.zmn.plat.services.interfaces.base.fault.FaultService;
import com.zmn.plat.services.interfaces.product.BaseCodeMapService;
import com.zmn.plat.services.interfaces.servcategory.CategoryFaultImageService;
import com.zmn.plat.services.interfaces.servcategory.ServAssCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 后端产品分类-故障图片业务接口实现类
 *
 * @author fengxuecai
 * @since 2021/11/25 14:30
 */
@Slf4j
@Service
public class CategoryFaultImageBServiceImpl implements CategoryFaultImageBService {

    @Resource
    private CategoryFaultImageService categoryFaultImageService;

    @Resource
    private ServAssCategoryService servAssCategoryService;

    @Resource
    private FaultService faultService;


    @Resource
    private BaseCodeMapService baseCodeMapService;

    @Override
    public FaultImageDRO getDefaultImageByServCategIdAndCategId(Integer servCategId, Integer categId) {

        if (NumberUtil.isNullOrZero(servCategId) || NumberUtil.isNullOrZero(categId)) {
            log.error("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategId入参为空,servCategId={},categId={}", servCategId, categId);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PANAM_NULL);
        }
        // 查询服务类型、产品分类关联
        List<ServAssCategoryVO> servAssCategories = servAssCategoryService.listByQuery(ServAssCategoryQuery.builder()
                .servCategId(servCategId)
                .categId(categId).build());
        if (CollectionUtil.isNullOrEmpty(servAssCategories)) {
            log.error("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategId未查到服务-产品分类关联,servCategId={},categId={}", servCategId, categId);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_RESULT_NULL);
        }
        ServAssCategoryVO servAssCategoryVO = servAssCategories.get(0);
        // 查询后端产品分类-故障图片(默认图片)
        List<CategoryFaultImage> categoryFaultImages = categoryFaultImageService.listByQuery(CategoryFaultImageQuery.builder()
                .groupId(servAssCategoryVO.getGroupId()).build());
        if (CollectionUtil.isNullOrEmpty(categoryFaultImages)) {
            log.error("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategId未查到产品分类-故障图片(默认图片)关联,groupId={}", servAssCategoryVO.getGroupId());
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_RESULT_NULL);
        }

        final Map<Integer, String> map = baseCodeMapFaultPart();
        FaultImageDRO faultImageDro = new FaultImageDRO();
        for (CategoryFaultImage categoryFaultImage : categoryFaultImages) {
            if (StringUtil.isNotBlank(categoryFaultImage.getDefaultImg())) {
                BeanUtils.copyProperties(categoryFaultImage, faultImageDro);
                faultImageDro.setPartTypeName(map.get(faultImageDro.getPartType()));
                break;
            }
        }
        return faultImageDro;
    }

    @Override
    public List<FaultImageDRO> listFaultImageByServCategIdAndCategIdAndFaultIds(Integer servCategId, Integer categId, List<Integer> faultIds) {

        if (NumberUtil.isNullOrZero(servCategId) || NumberUtil.isNullOrZero(categId) || CollectionUtil.isNullOrEmpty(faultIds)) {
            log.error("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategIdAndFaultIds入参为空,servCategId={},categId={},faultIds={}", servCategId, categId, faultIds);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PANAM_NULL);
        }
        // 查询服务类型、产品分类关联
        List<ServAssCategoryVO> servAssCategories = servAssCategoryService.listByQuery(ServAssCategoryQuery.builder()
                .servCategId(servCategId)
                .categId(categId).build());
        List<FaultImageDRO> faultImageList = new ArrayList<>();
        if (CollectionUtil.isNullOrEmpty(servAssCategories)) {
            log.error("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategIdAndFaultIds未查到服务-产品分类关联,servCategId={},categId={}", servCategId, categId);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_RESULT_NULL);
        }
        ServAssCategoryVO servAssCategoryVO = servAssCategories.get(0);
        // 查询后端产品分类-故障图片
        List<CategoryFaultImage> categoryFaultImages = categoryFaultImageService.listByQuery(CategoryFaultImageQuery.builder()
                .groupId(servAssCategoryVO.getGroupId()).build());
        if (CollectionUtil.isNullOrEmpty(categoryFaultImages)) {
            log.error("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategIdAndFaultIds未查到产品分类-故障图片关联,groupId={}", servAssCategoryVO.getGroupId());
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_RESULT_NULL);
        }
        // 查询具体故障
        List<Fault> faults = faultService.listByQuery(FaultQuery.builder().status(GlobalConsts.YES).faultIds(faultIds).build());
        if (CollectionUtil.isNullOrEmpty(faults)) {
            log.info("CategoryFaultImageBServiceImpl.listFaultImageByServCategIdAndcategIdAndFaultIds未查到有效具体故障,faultIds={}", faultIds);
            return faultImageList;
        }
        // 获取有效故障id集合
        List<Integer> effectiveFaultIds = faults.stream().map(Fault::getFaultId).collect(Collectors.toList());
        Map<Integer, String> faultMap = faults.stream().collect(Collectors.toMap(Fault::getFaultId, Fault::getFaultName));

        // 取有效故障关联故障图片
        final Map<Integer, String> map = baseCodeMapFaultPart();
        categoryFaultImages.forEach(categoryFaultImage -> {
            if (StringUtil.isNotBlank(categoryFaultImage.getFaultRelevance())) {
                List<Integer> faultRelevance = StringToArrayUtil.convertStrsToList(categoryFaultImage.getFaultRelevance());
                if (CollectionUtil.isNotNullOrEmpty(faultRelevance)) {
                    // 取出故障图片关联有效的具体故障ids
                    List<Integer> intersection = faultRelevance.stream().filter(effectiveFaultIds::contains).collect(Collectors.toList());
                    if (CollectionUtil.isNotNullOrEmpty(intersection)) {
                        FaultImageDRO faultImageDro = new FaultImageDRO();
                        BeanUtils.copyProperties(categoryFaultImage, faultImageDro);
                        faultImageDro.setPartTypeName(map.get(faultImageDro.getPartType()));
                        List<VtDTO> vts = new ArrayList<>();
                        intersection.forEach(e -> vts.add(new VtDTO(e, faultMap.get(e))));
                        faultImageDro.setFaultRelevance(vts);
                        faultImageList.add(faultImageDro);
                    }
                }
            }
        });
        return faultImageList;

    }

    /**
     * 获取码表中故障部位
     *
     * @return
     */
    private Map<Integer, String> baseCodeMapFaultPart() {
        BaseCodeMapQuery query = new BaseCodeMapQuery();
        query.setOneTypeId(BaseCodeMapConsts.BASE_CODE_MAP_ONE_TYPE_NUMBER_FAULT_PART);
        query.setStatus(GlobalConsts.YES);
        List<BaseCodeMap> baseCodeMaps = baseCodeMapService.listByQuery(query);
        if (Objects.isNull(baseCodeMaps)) {
            return new HashMap<>();
        }
        return baseCodeMaps.stream().collect(Collectors.toMap(BaseCodeMap::getThreeTypeId, BaseCodeMap::getName));
    }

}
